const http = require("http");
const url = require("url");

let invokeMethod = {};

let app = function (req, res) {
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
    let pathName = url.parse(req.url).pathname;
    // if (!pathName.endsWith("/")) {
    //     pathName += "/";
    // }
    if (pathName !== "/favicon.ico") {
        try {
            invokeMethod[pathName](req, res);
        } catch (e) {
            res.end("404 no router!");
        }
    }
}

app.get = function (pathName, callback) {
    invokeMethod[pathName] = callback;
    /*这是在注册方法，实际效果如下：
    invokeMethod["/login"] = function (req, res) {
        console.log("this is app.get()");
    }*/
}

app.post = function (pathName, callback) {
    invokeMethod[pathName] = callback;
}

//通过http.createServer执行了app方法，触发执行了invokMethod的注册方法
http.createServer(app).listen(8080);

//执行首页的app.get()注册方法
app.get("/", function (req, res) {
    res.end("this is app.get() to home");
});

//执行登录页面的app.get()注册方法
app.get("/login", function (req, res) {
    res.end("this is app.get() to login");
});

//执行登录表单提交的app.post()注册方法
app.post("/dologin", function (req, res) {
    res.end("this is app.post() to dologin");
});